package gopacket

import (
	"fmt"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
	"log"
)

func catchTls() {
	var (
		device            = "\\Device\\NPF_{C2BCFD65-FE5E-4870-B60B-EB99F308BF2B}" // 修改为你的网络接口
		snapshotLen int32 = 1024
		promiscuous       = false
		timeout           = pcap.BlockForever
		handle      *pcap.Handle
		err         error
	)

	// 打开设备
	handle, err = pcap.OpenLive(device, snapshotLen, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()

	// 设置过滤器
	var filter = "tcp" // 捕获所有 TCP 流量
	err = handle.SetBPFFilter(filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Capturing all TCP packets.")

	// 使用 gopacket 处理数据包
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		// 解析数据包
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			tcp, _ := tcpLayer.(*layers.TCP)

			if len(tcp.Payload) > 0 {
				payload := tcp.Payload

				// 检查 TLS 协议
				switch payload[0] {
				case 0x14:

					fmt.Println("Captured TLS Change Cipher Spec packet")
				case 0x15:
					fmt.Println("Captured TLS Alert packet")
				case 0x16:
					fmt.Println("Captured TLS Handshake packet")
				case 0x17:
					fmt.Println("Captured TLS Application Data packet")
				}

				// 打印来源和目的地 IP 地址
				if netLayer := packet.NetworkLayer(); netLayer != nil {
					srcIP, dstIP := netLayer.NetworkFlow().Endpoints()
					srcPort, dstPort := tcp.SrcPort, tcp.DstPort
					fmt.Printf("From %s:%d to %s:%d\n", srcIP, srcPort, dstIP, dstPort)
				}
			}
		}
	}
}

func tlsDecodeCipher() {
	//tls.Dial()

}
